
package com.et.book.services;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.util.Vector;

import com.et.book.fenghuangchi.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.drawable.Drawable;
import android.os.Environment;

public class BookService {

	private String BOOK_NAME = "";
	
	private File book_file = null;
	private MappedByteBuffer m_mbBuf = null;
	private int m_mbBufLen = 0;
	private int m_mbBufBegin = 0;
	private int m_mbBufEnd = 0;
	private String m_strCharsetName = "GBK";
	private Drawable m_book_bg = null;
	private int mWidth;
	private int mHeight;

	private Vector<String> m_lines = new Vector<String>();

	private int m_fontSize = 30;
	private int m_textColor = Color.BLACK;
	private int m_backColor = Color.rgb(226, 229, 151); // 背景颜色
	private int marginWidth = 15; // 左右与边缘的距离
	private int marginHeight = 20; // 上下与边缘的距离
	private int lineSpace = 2;//行间距

	private int mLineCount; // 每页可以显示的行数
	private float mVisibleHeight; // 绘制内容的宽
	private float mVisibleWidth; // 绘制内容的宽
	private boolean m_isfirstPage,m_islastPage;
	
	private Paint mPaint;

	private Context context = null;
	
	public BookService(int w, int h ,Context ctx) {
		context = ctx;
		mWidth = w;
		mHeight = h;
		m_fontSize = context.getResources().getDimensionPixelSize(R.dimen.text_size);
		lineSpace = context.getResources().getDimensionPixelSize(R.dimen.line_space);
		marginWidth = context.getResources().getDimensionPixelSize(R.dimen.margin_width);
		marginHeight = context.getResources().getDimensionPixelSize(R.dimen.margin_height);
		BOOK_NAME = context.getResources().getString(R.string.app_name);
		mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		mPaint.setTextAlign(Align.LEFT);
		mPaint.setTextSize(m_fontSize);
		mPaint.setColor(m_textColor);
		mVisibleWidth = mWidth - marginWidth * 2;
		mVisibleHeight = mHeight - marginHeight * 2;
		mLineCount = (int) (mVisibleHeight / (m_fontSize+lineSpace)); // 可显示的行数
		m_book_bg = context.getResources().getDrawable(R.drawable.book_bg);
		m_book_bg.setBounds(0, 0, mWidth, mHeight);
	}

	
	public void openbook() {
		InputStream in = null;
		BufferedInputStream bin = null;
		BufferedOutputStream bout = null;
		try {
			book_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+BOOK_NAME+"/data.rtx");
			//书籍不存在，将他从assets目录拷贝到对应目录
			if (!book_file.exists()) {
				File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+BOOK_NAME);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				book_file.createNewFile();
				
				String[] files = context.getResources().getAssets().list("");
				FileOutputStream fout = new FileOutputStream(book_file);
				bout = new BufferedOutputStream(fout);
				
				if (files!=null&&files.length>0) {
					for (int i = 0; i < files.length; i++) {
						if (files[i]!=null&&files[i].indexOf(".txt")!=-1) {
							if (in!=null) {
								in.close();
							}
							if (bin!=null) {
								bin.close();
							}
							
							in = context.getResources().getAssets().open(files[i]);
							bin = new BufferedInputStream(in);
							byte[] bytes = new byte[1024];
							int len = 0;
							while ((len = bin.read(bytes)) != -1) {
								bout.write(bytes, 0, len);					
							}
						}
					}
				}
				
			}
			
			long lLen = book_file.length();
			m_mbBufLen = (int) lLen;
			m_mbBuf = new RandomAccessFile(book_file, "r").getChannel().map(
					FileChannel.MapMode.READ_ONLY, 0, lLen);
		} catch (Exception e) {
		}finally{
			try {
				bout.flush();
				bout.close();
				bin.close();
			} catch (Exception e2) {
			}
		}
		
		
	}
	
	/**
	 * 从nFromPos开始向文件头部读取一个段落
	 * @param nFromPos
	 * @return
	 */
	protected byte[] readParagraphBack(int nFromPos) {
		int nEnd = nFromPos;
		int i;
		byte b0, b1;
		if (m_strCharsetName.equals("UTF-16LE")) {
			i = nEnd - 2;
			while (i > 0) {
				b0 = m_mbBuf.get(i);
				b1 = m_mbBuf.get(i + 1);
				if (b0 == 0x0a && b1 == 0x00 && i != nEnd - 2) {
					i += 2;
					break;
				}
				i--;
			}

		} else if (m_strCharsetName.equals("UTF-16BE")) {
			i = nEnd - 2;
			while (i > 0) {
				b0 = m_mbBuf.get(i);
				b1 = m_mbBuf.get(i + 1);
				if (b0 == 0x00 && b1 == 0x0a && i != nEnd - 2) {
					i += 2;
					break;
				}
				i--;
			}
		} else {
			i = nEnd - 1;
			while (i > 0) {
				b0 = m_mbBuf.get(i);
				if (b0 == 0x0a && i != nEnd - 1) {
					i++;
					break;
				}
				i--;
			}
		}
		if (i < 0)
			i = 0;
		int nParaSize = nEnd - i;
		int j;
		byte[] buf = new byte[nParaSize];
		for (j = 0; j < nParaSize; j++) {
			buf[j] = m_mbBuf.get(i + j);
		}
		return buf;
	}


	/**
	 * 从nFromPos位置开始，向文件尾部读取一个段落
	 * @param nFromPos
	 * @return
	 */
	protected byte[] readParagraphForward(int nFromPos) {
		int nStart = nFromPos;
		int i = nStart;
		byte b0, b1;
		// 根据编码格式判断换行
		if (m_strCharsetName.equals("UTF-16LE")) {
			while (i < m_mbBufLen - 1) {
				b0 = m_mbBuf.get(i++);
				b1 = m_mbBuf.get(i++);
				if (b0 == 0x0a && b1 == 0x00) {
					break;
				}
			}
		} else if (m_strCharsetName.equals("UTF-16BE")) {
			while (i < m_mbBufLen - 1) {
				b0 = m_mbBuf.get(i++);
				b1 = m_mbBuf.get(i++);
				if (b0 == 0x00 && b1 == 0x0a) {
					break;
				}
			}
		} else {
			while (i < m_mbBufLen) {
				b0 = m_mbBuf.get(i++);
				if (b0 == 0x0a) {
					break;
				}
			}
		}
		int nParaSize = i - nStart;
		byte[] buf = new byte[nParaSize];
		for (i = 0; i < nParaSize; i++) {
			buf[i] = m_mbBuf.get(nFromPos + i);
		}
		return buf;
	}

	/**
	 * 从m_mbBufEnd位置开始向文件尾部读取一页内容
	 * @return
	 */
	protected Vector<String> pageDown() {
		String strParagraph = "";
		Vector<String> lines = new Vector<String>();
		while (lines.size() < mLineCount && m_mbBufEnd < m_mbBufLen) {
			byte[] paraBuf = readParagraphForward(m_mbBufEnd); // 读取一个段落
			m_mbBufEnd += paraBuf.length;
			try {
				strParagraph = new String(paraBuf, m_strCharsetName);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String strReturn = "";
			if (strParagraph.indexOf("\r\n") != -1) {
				strReturn = "\r\n";
				strParagraph = strParagraph.replaceAll("\r\n", "");
			} else if (strParagraph.indexOf("\n") != -1) {
				strReturn = "\n";
				strParagraph = strParagraph.replaceAll("\n", "");
			}

//			if (strParagraph.length() == 0) {
//				lines.add(strParagraph);
//			}
			while (strParagraph.length() > 0) {
				int nSize = mPaint.breakText(strParagraph, true, mVisibleWidth,
						null);
				lines.add(strParagraph.substring(0, nSize));
				strParagraph = strParagraph.substring(nSize);
				if (lines.size() >= mLineCount) {
					break;
				}
			}
			if (strParagraph.length() != 0) {
				try {
					m_mbBufEnd -= (strParagraph + strReturn)
							.getBytes(m_strCharsetName).length;
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return lines;
	}
	/**
	 * 从m_mbBufEnd位置开始向文件头部读取一页内容
	 */
	protected void pageUp() {
		if (m_mbBufBegin < 0)
			m_mbBufBegin = 0;
		Vector<String> lines = new Vector<String>();
		String strParagraph = "";
		while (lines.size() < mLineCount && m_mbBufBegin > 0) {
			Vector<String> paraLines = new Vector<String>();
			byte[] paraBuf = readParagraphBack(m_mbBufBegin);
			m_mbBufBegin -= paraBuf.length;
			try {
				strParagraph = new String(paraBuf, m_strCharsetName);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			strParagraph = strParagraph.replaceAll("\r\n", "");
			strParagraph = strParagraph.replaceAll("\n", "");

//			if (strParagraph.length() == 0) {
//				paraLines.add(strParagraph);
//			}
			while (strParagraph.length() > 0) {
				int nSize = mPaint.breakText(strParagraph, true, mVisibleWidth,
						null);
				paraLines.add(strParagraph.substring(0, nSize));
				strParagraph = strParagraph.substring(nSize);
			}
			lines.addAll(0, paraLines);
		}
		while (lines.size() > mLineCount) {
			try {
				m_mbBufBegin += lines.get(0).getBytes(m_strCharsetName).length;
				lines.remove(0);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		m_mbBufEnd = m_mbBufBegin;
		return;
	}

	public void prePage() throws IOException {
		if (m_mbBufBegin <= 0) {
			m_mbBufBegin = 0;
			m_isfirstPage=true;
			return;
		}else m_isfirstPage=false;
		m_lines.clear();
		pageUp();
		m_lines = pageDown();
	}

	public void nextPage() throws IOException {
		if (m_mbBufEnd >= m_mbBufLen) {
			m_islastPage=true;
			return;
		}else m_islastPage=false;
		m_lines.clear();
		m_mbBufBegin = m_mbBufEnd;
		m_lines = pageDown();
	}

	/**
	 * 到任意一页
	 * @param page 页数
	 * @throws IOException
	 */
	public void gotoPage(int page)throws IOException{
		m_mbBufBegin = page;
		prePage();
	}
	
	
	
	public void drawPage(Canvas c) {
		if (m_lines.size() == 0)
			m_lines = pageDown();
		if (m_lines.size() > 0) {
			if (m_book_bg == null)
				c.drawColor(m_backColor);
			else
				m_book_bg.draw(c);
			int y = marginHeight+marginHeight*2/3 - m_fontSize;
			for (String strLine : m_lines) {
				y += m_fontSize + lineSpace;
				c.drawText(strLine, marginWidth, y, mPaint);
			}
		}
		
		float textsize = mPaint.getTextSize();
		mPaint.setTextSize(textsize*4/5f);
		float fPercent = (float) (m_mbBufEnd * 1.0 / m_mbBufLen);
		DecimalFormat df = new DecimalFormat("#0.0");
		String strPercent = df.format(fPercent * 100) + "%";
		int nPercentWidth = (int) mPaint.measureText("999.9%") + 1;
		c.drawText(strPercent, mWidth - nPercentWidth, mHeight - 5, mPaint);
		mPaint.setTextSize(textsize);
		
	}

	public void setBgBitmap(Drawable BG) {
		m_book_bg = BG;
	}
	
	public boolean isfirstPage() {
		return m_mbBufBegin<=0;
	}
	public boolean islastPage() {
		return m_mbBufEnd>=m_mbBufLen;
	}
	
	public int getCurrentPage(){
		return m_mbBufBegin;
	}
	
	public int getToatalPage(){
		return m_mbBufLen;
	}
	
	public String getCurentPecent(){
		float fPercent = (float) (m_mbBufEnd * 1.0 / m_mbBufLen);
		DecimalFormat df = new DecimalFormat("#0.0");
		String strPercent = df.format(fPercent * 100) + "%";
		return strPercent;
	}
}
